<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/16
 * Time: 21:00
 */
namespace Pay\Controller;

use Common\Common\Api\Order;

/**
 * Class ManyiController
 * @package Pay\Controller
 * 微宝付
 */
class WeibaoController extends PayController{
    protected $config;
    protected $class;

    public function __construct(){
        parent::__construct();
        $classes = explode("\\",__CLASS__);
        $class = end($classes);
        $this->class = substr($class, 0, stripos($class, "Controller"));
    }

    public function pay($array)
    {
        $this->config = M("Channel")->where(array('id' => $array['channel']))->find();

        if (!$this->config) {
            $this->showmessage('通道错误!', ['code' => C("THIRDCODES." . $this->class)]);
        }

        $parameter = array(
            'code' => $this->config['code'], // 通道名称
            'title' => $this->config['title'],
            'exchange' => 1, // 金额比例
            'gateway' => $this->config['gateway'],
            'orderid' => createOrderId(),
            'out_trade_id' => I("request.pay_orderid"),
            'body' => 'pay',
            'channel' => $array
        );

        $return = $this->orderadd($parameter);

        $data = array();
        $data['payKey'] = $this->config['mch_id'];
        $data['orderPrice'] = number_format($return['amount'], 2, '.', '');
        $data['outTradeNo'] = $return['orderid'];

        switch ($this->config['paytype']) {
            //银联快捷
            case 13:
                $data['productType'] = '90000103';
                break;
            //银联扫码
            case 11:
                $data['productType'] = '60000103';
                break;
            //支付宝扫码
            case 3:
                $data['productType'] = '20000203';
                break;
            //支付宝H5
            case 4:
                $data['productType'] = '20000203';
                break;
            //支付宝扫码
            case 17:
                $data['productType'] = '20000203';
                break;
            //支付宝H5
            case 18:
                $data['productType'] = '20000203';
                break;
            default:
                $this->showmessage('该通道不支持此方式!', ['code' => C("THIRDCODES." . $this->class)]);
        }

        //$data['secretContent'] = '';

        $data['orderTime'] = date("YmdHis", time());
        $data['productName'] = 'zf';
        $data['orderIp'] = getIP();
        $data['remark'] = 'zf';
        $data['notifyUrl'] = $return['notifyurl'];
        $data['returnUrl'] = $return['callbackurl'];
        $data['subPayKey'] = $this->config['appsecret'];

        ksort($data);
        $str = httpstr($data) . "&paySecret=" . $this->config['signkey'];
        $data['sign'] = strtoupper(md5($str));

        switch ($this->config['paytype']) {
            //银联快捷
            case 13:
                po($this->config['gateway'], $data);
                exit;
                break;
            default:
        }

        /*$apiurl = $this->config['gateway'];

        $apiurl .= "?";
        foreach ($data as $k => $v) {
            $apiurl .= $k . "=" . $v . "&";
        }
        $apiurl = substr($apiurl, 0, -1);


        $res = curl_get($apiurl);
        $res = json_decode($res, true);*/

        $res = curl($this->config['gateway'], httpstr($data));
		$res = json_decode($res, true);
		
        $code = $res['payMessage'];

        if(!$code){
            if($res['errMsg']){
                $this->showmessage($res['errMsg'], ['code' => C("THIRDCODES." . $this->class)]);
            }

            if($res['message']){
                $this->showmessage($res['errMsg'], ['code' => C("THIRDCODES." . $this->class)]);
            }
            
            $this->showmessage('未获取到支付链接!', ['code' => C("THIRDCODES." . $this->class)]);
        }

        $paytype = transArr( C("PAYTYPES"), "id");

        $this->assign("wap_url", $code);
        //$this->assign("code_url", $res['data']['payurl']);
        $this->assign("title", $paytype[$this->config['paytype']]);
        $this->assign("return", $return);
        $this->assign("imgurl", C("website.DOMAIN")."/Pay_Qrcode_getCode?type=1&data=" . $code);

        switch($this->config['paytype']){
            //微信
            case 1:
                $this->display("WeiXin/weixin");
                break;
            //支付宝扫码
            case 3:
                //支付宝H5
            case 4:
            case 17:
            case 18:
				echo $code; exit;
                if(isMobile()){
                    $this->display("WeiXin/alipaywap");
                }else{
                    $this->display("WeiXin/alipay");
                }
                break;
			case 11:
				//header("location:{$code}"); exit;
				$this->display("WeiXin/Pay");
			break;
            default:
                $this->display("WeiXin/Pay");
        }
    }

    //通知
    public function notifyurl(){
		$this->debug_callback();

        $p = empty($_GET) ? $_POST : $_GET;

        if(!$p || empty($p)){
            exit;
        }

        //获取订单信息
        $orderid = $p['outTradeNo'];
        $find = $this->checkOrderNotify($orderid);
        if(!$find){
            echo 'order_not_found'; exit;
        }

        //保存回调数据
        $s = file_get_contents('php://input');
        M("Order")->where(array("pay_orderid"=>$orderid))->save(array(


            "pay_orderid_rd"=>htmlspecialchars($p['trxNo'])));
        Order::getInstance()->edit($find['id'],array(

            "pay_orderid_rd"=>htmlspecialchars($p['trxNo'])));

        //获取渠道信息
        $this->config = M("Channel")->where(array('code'=>$this->class))->find();

        $sign = $p['sign'];
        unset($p['sign']);

        ksort($p);
        $str = arrToUrlStr($p)."&paySecret=".$this->config['signkey'];
        $sign2 = strtoupper(md5($str));

        if($sign != $sign2){
            echo 'sign_wrong';exit;
        }

        if($p['tradeStatus'] != 'SUCCESS'){
            echo 'pay_fail';exit;
        }

        //处理支付
        $this->async($find['pay_orderid'],"SUCCESS");
    }

    public function callBackUrl(){

        echo '支付成功'; exit;
    }
}
